//
//  LoginViewController.m
//  DPGJ
//
//  Created by ZhuoLaiQiang@Gmail.com on 11-11-17.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "LoginViewController.h"
#import "URLFactory.h"
#import "RequestTokenOperation.h"
#import "CONSTS.h"
#import "RootViewController.h"


@interface LoginViewController()

- (void)returnToRootViewController;

- (void)requestToken;
- (void)successRequestToken;
- (void)failRequestToken:(NSString *)reasonStr;

@end

@implementation LoginViewController

@synthesize loginWebView;
@synthesize loginUrl                    =       _loginUrl;
@synthesize getTokenOperationQueue      =       _getTokenOperationQueue;

#pragma mark - 系统函数
- (void)dealloc
{
    [_getTokenOperationQueue cancelAllOperations];
    LF_RELEASE_SAFELY(_getTokenOperationQueue);
    
    loginWebView.delegate = nil;
    [loginWebView stopLoading];
    
    LF_RELEASE_SAFELY(loginWebView);
    LF_RELEASE_SAFELY(_loginUrl);
    
    [super dealloc];
}

- (id)initWithLoginUrl:(NSString *)loginUrlP
{
    self = [super init];
    if (self) 
    {
        self.loginUrl = loginUrlP;
    }
    
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.title = @"登陆";
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle: @"返回" 
                                                                              style: UIBarButtonItemStylePlain 
                                                                             target: self 
                                                                             action: @selector(returnToRootViewController)] autorelease];
    [MBProgressHUD showHUDAddedTo: self.view animated: NO];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [self performSelector: @selector(getDataFromNetwork) withObject: nil afterDelay: 1.4];
}

- (void)getDataFromNetwork
{
    NSURLRequest *requst = [NSURLRequest requestWithURL: [NSURL URLWithString: _loginUrl]];
    [loginWebView loadRequest: requst];
}

- (void)viewDidUnload
{
    [self setLoginWebView:nil];
    [super viewDidUnload];
}

#pragma mark - 自定义函数
- (void)returnToRootViewController
{
    NSObject<EPGLTransitionViewDelegate> *transition;
    
    transition = [[[Demo3Transition alloc] init] autorelease];
    
    EPGLTransitionView *glview = [[[EPGLTransitionView alloc] 
                                   initWithView:self.navigationController.view
                                   delegate:transition] autorelease];
    
    
    [self.navigationController dismissModalViewControllerAnimated: YES];
    
    [glview prepareTextureTo: g_rootViewController.navigationController.view]; 
    [glview setClearColorRed:0.0
                       green:0.0
                        blue:0.0
                       alpha:1.0];
    
    [glview startTransition];
}

- (void)requestToken
{
    @autoreleasepool
    {
        RequestTokenOperation *requestTokenOperation = [[[RequestTokenOperation alloc] 
                                                         initWithDelegat: self 
                                                         successSel: @selector(successRequestToken) 
                                                         failSel: @selector(failRequestToken:)] autorelease];
        
        self.getTokenOperationQueue = [[[NSOperationQueue alloc] init] autorelease];
        [_getTokenOperationQueue addOperation: requestTokenOperation];
    }
}

//成功获取token
- (void)successRequestToken
{
    [MBProgressHUD hideHUDForView: self.view.window animated: YES];
    [self.navigationController dismissModalViewControllerAnimated: YES];
    
    showAlert(nil, @"成功登陆");
}

- (void)failRequestToken:(NSString *)reasonStr
{
    [MBProgressHUD hideHUDForView: self.view.window animated: YES];
#ifdef DEBUG
    showAlert(ALERT_TITLE, reasonStr);
#else
    showAlert(ALERT_TITLE, ALERT_MESSAGE);
#endif
    
    [self.navigationController dismissModalViewControllerAnimated: YES];
}

#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    //ITTDINFO(@"%@", [request URL]);
    NSString *url = [[request URL] absoluteString];
    if ([url rangeOfString: CALL_BACK_URL].location != NSNotFound)  //如果发现
    {
        return NO;
    }
    
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [MBProgressHUD hideHUDForView: self.view  animated: YES];
    MBProgressHUD *mBProgressHUD = [MBProgressHUD showHUDAddedTo: self.view animated: YES];
    mBProgressHUD.labelText = MBPROGRESSHUD_MESSAGE;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [MBProgressHUD hideHUDForView: self.view animated: YES];
    
    NSString *lJs = @"document.documentElement.innerHTML";
    NSString *lHtml1 = [webView stringByEvaluatingJavaScriptFromString:lJs];
    // ITTDINFO(@"%@", lHtml1);
    
    if ([lHtml1 rangeOfString: @"第三方应用环境"].location != NSNotFound)   //检索html代码中是否有授权成功的标志 “跳转”
    {
        MBProgressHUD *mBProgressHUD = [[[MBProgressHUD alloc] initWithWindow: self.view.window] autorelease];
        [self.view.window addSubview: mBProgressHUD];
        mBProgressHUD.labelText = REQUEST_TOKEN;
        [mBProgressHUD show: YES];
        
        [self requestToken];
    }
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [MBProgressHUD hideHUDForView: self.view animated: YES];
    
    //showAlert(ALERT_TITLE, ALERT_MESSAGE);
}

@end
